
//
//  OAuthViewController.m
//  Weibo2
//
//  Created by Gate on 15/11/24.
//  Copyright © 2015年 Gate. All rights reserved.
//

#import "OAuthViewController.h"
#import "AFNetworking.h"
#import "Account.h"
#import "AccountTool.h"
#import "MBProgressHUD+MJ.h"
#import "Tool.h"
//2.00LH9L6DUJo9gEd4b58b6c280Efgws----------accessToken
@interface OAuthViewController ()<UIWebViewDelegate>

@end

@implementation OAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIWebView *webView = [[UIWebView alloc] init];
    webView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    
    webView.delegate = self;
    [self.view addSubview:webView];
    
    //加载数据https://api.weibo.com/oauth2/authorize?client_id=4292003412&redirect_uri=http://www.baidu.com
    NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=4292003412&redirect_uri=http://www.baidu.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}
#pragma mark - webView代理方法
/**
 *  webView开始发送请求的时候就会调用*/
 
//- (void)webViewDidStartLoad:(UIWebView *)webView
//{
//    // 显示提醒框
//    [MBProgressHUD showMessage:@"正在加载..."];
//}
//
//
// /**  webView请求完毕的时候就会调用*/
//
//- (void)webViewDidFinishLoad:(UIWebView *)webView
//{
//    // 隐藏提醒框
//    [MBProgressHUD hideHUD];
//}

/**
 *  webView请求失败的时候就会调用
 */
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    // 隐藏提醒框
    [MBProgressHUD hideHUD];
}
/**
 *  当webView发送一个请求之前，都会先调用这个方法，询问代理可不可以加载这个页面（请求）
 *
 *  @param request        <#request description#>
 *
 *  @return YES：可以加载这个页面   NO：不可以加载这个页面
 */
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    // 请求的URl路径
    NSString *urlStr = [request.URL absoluteString];
    // 查找code=在urlStr中的范围
    NSRange range = [urlStr rangeOfString:@"code="];
    //range.length 是否为nil
    if (range.location != NSNotFound) {
        //截取code=后面的请求标记（经过用户授权成功地）
        NSInteger loc = range.location + range.length;
        NSString *codeLong = [urlStr substringFromIndex:loc];
        NSLog(@"urlStr-----%@------codeLong---------%@",urlStr,codeLong);
        //发送信息给新浪，通过code换取accessToken
        
        [self accessTokenWithCode:codeLong];
        
        
//        NSRange rangeFrom = [urlStr rangeOfString:@"&from"];
//        if (rangeFrom.length) {
//            
//            NSInteger locFrom = rangeFrom.location;
//            NSString *code = [codeLong substringToIndex:locFrom];
//            [self accessTokenWithCode:codeLong];
//            NSLog(@" 真正的code是------------%@",codeLong);
//            
//        }
    }
    return YES;
}
/*
 client_id	true	string	申请应用时分配的AppKey。
 client_secret	true	string	申请应用时分配的AppSecret。
 grant_type	true	string	请求的类型，填写authorization_code
 
 grant_type为authorization_code时
 必选	类型及范围	说明
 code	true	string	调用authorize获得的code值。
 redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
*/
- (void)accessTokenWithCode:(NSString *)code{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"client_id"] = @"4292003412";
    params[@"client_secret"] = @"e5477590673a026208893d6108702e3b";
    params[@"grant_type"] = @"authorization_code";
    params[@"code"] = code;
    params[@"redirect_uri"] = @"http://www.baidu.com";
    [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        // 4.先将字典转为模型
        Account *account = [Account accountWithDict:responseObject];
        // 5.存储模型数据
        [AccountTool saveAccount:account];
        // 6.新特性\去首页
        [Tool chooseRootViewController];
        // 7.隐藏提醒框
        [MBProgressHUD hideHUD];
        NSLog(@"成功成功成功成功成功");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"失败----------------------%@",error);
    }];

}
@end

//        //创建请求管理类
////        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
////        //接受对象为json
////        mgr.responseSerializer = [AFJSONResponseSerializer serializer];
////        //封装请求参数
////        NSMutableDictionary *params = [NSMutableDictionary dictionary];
////        params[@""]  = @"123wwww";
////        //发送请求
////        [mgr POST:@"https" parameters:params
////          success:^(AFHTTPRequestOperation *operation, id responseObject) {
////
////              //将字典转为模型
////              Account *account = [Account accountWithDict:responseObject];
////
////              NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
////              NSString *file = [doc stringByAppendingPathComponent:@"account.data"];
////              //存储模型数据
////              [NSKeyedArchiver archiveRootObject:account toFile:file];
////
////        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
////
////        }];
////
//    }
//    return YES;
//}
//- (void)accessTokenWithCode:(NSString *)code{
//
//    // 1.创建请求管理对象
//    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
//    // 说明服务器返回的JSON数据
//    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
//
//    // 2.封装请求参数
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    params[@"client_id"] = @"14292003412";
//    params[@"client_secret"] = @"e5477590673a026208893d6108702e3b";
//    params[@"grant_type"] = @"authorization_code";
//    params[@"code"] = code;
//    params[@"redirect_uri"] = @"http://www.baidu.com";
//
//    // 3.发送请求
//    [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:params
//      success:^(AFHTTPRequestOperation *operation, id responseObject) {
//          // 4.先将字典转为模型
//          Account *account = [Account accountWithDict:responseObject];
//
//          // 5.存储模型数据
//          [AccountTool saveAccount:account];
//
//          // 6.新特性\去首页
//          [Tool chooseRootViewController];
//
//          //7.隐藏
//          [MBProgressHUD hideHUD];
//      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
////          隐藏
//          [MBProgressHUD hideHUD];
//                }];
//
//}



